function [datasetyb] = APEuvvissurfbin(datax,datay,ny)
%UVVISSURFBIN(datax,datay,ny)
% Bin time slices of ANDOR ASCII kinetic dataset, then plot
%
% INPUT:  datax :   Filename string, extension '.mat' is assumed
%                   Need to have run uvvisload first
%            ny :   Number of time slices to bin
% 
% OUTPU:  datasetyb :   modified datay array
% Example:
%   >> uvvissurfbin(ramandatax, ALSdatay, 50)

% Help if called without argument
if nargin<3,
    help uvvissurfbin
    return
end

% try, load(datasetname)
% catch,
%   disp(strvcat('Ooops! :',' ',lasterr,' ','Need to have run uvvisload first'))
%   return
% end

% Bin datay with ncol columns along rows, to mean of nbin rows
datasetyb=rowbin(datay',ny,length(datax));

% ------
figure(2)
surf(datax, ny*(1:size(datasetyb,1)) , datasetyb)
axis tight
shading interp
view(20,30)
xlabel('Wavelength [nm]')
ylabel('Time slice [Accumulation]')
zlabel('Absorbance')
title(['Surface, ybin',num2str(ny)])

% ------
figure(3)
M=ones(size(datasetyb,1),1); B=[0 0 1]; G=[0 1 0]; R=[1 0 0];
ColorOrder=M*B; ColorOrder(1,:)=G; ColorOrder(end,:)=R;
set(gca,'NextPlot','replacechildren','ColorOrder',ColorOrder)
plot(datax, datasetyb)
axis tight
xlabel('Wavelength [nm]')
ylabel('Absorbance')
title(['Plot from green to red, ybin',num2str(ny)])

% % ------
% figure
% ribbon(datax, datasetyb')
% shading interp
% set(gca,'xdir','reverse')
% view(95,10)
% title(['Ribbons, ybin',num2str(ny)])


function AvgF = rowbin(a,nbin,ncol)
% Bin Matrix a with ncol columns along rows, to mean of nbin rows
% From
% http://stackoverflow.com/questions/1787057/how-should-i-perform-this-binning-and-averaging-in-matlab

nRemove = rem(size(a,1),nbin);      % Find the number of points to remove
a = a(1:end-nRemove,:);             % Trim points to make an even multiple of nbin
Avg = mean(reshape(a,nbin,[],ncol));
AvgF = squeeze(Avg);
